package com.example.music;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

public class MusicService extends Service {
    public MusicService() {
    }
    MediaPlayer player;
    @Override
    public void onCreate() {//初始化 player
        super.onCreate();
        Log.i("msg", "onCreate()");
        player= MediaPlayer.create(this,R.raw.qifnegle);
    }
    @Override
    public void onDestroy() {//销毁 player
        super.onDestroy();
        Log.i("msg ", "onDestroy()");
        if (player!=null){
            player.stop();
            player.release();//释放 MediaPlayer 对象
        }
    }
    @Override
    public boolean onUnbind(Intent intent) {
        Log.i("msg ", "onUnbind()");
        return super.onUnbind(intent);
    }
    @Override
    public IBinder onBind(Intent intent) {
        Log.i("msg ", "onBind()");
        return new MusicBinder();
    }
    class MusicBinder extends Binder {
        public MusicService getService() {
            return MusicService.this;
        }
    }
    public void play(){
        if (player==null){
            player=MediaPlayer.create(this,R.raw.qifnegle);
            player.start();
            return;
        }
        if (player!=null && !player.isPlaying()){//暂停状态
            player.start();
            return;
        }
        if (player!=null && player.isPlaying()){//播放状态,重新播放
            player.seekTo(0);
            player.start();
            return;
        }
    }
    public void pause(){
        if (player!=null && player.isPlaying()){
            player.pause();
        }
    }
    public MediaPlayer getPlayer(){
        return player;
    }
    public void stop(){
        if (player!=null ){
            player.stop();
            player.prepareAsync();
        }
    }


}
